<template>
    <Layout>
        <Form ref="form1"   :label-width="120">
            <Row class="query-form" style="padding-top: 15px">
                <Col span="8">
                     <FormItem label="设备类型名称：">
                        <Input class="query-form-el" v-model="form1.deviceTypeName" ></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                     <FormItem label="所属公司：">
                        <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName' :orgTree="true"
                          :setCurrentName="{label:form1.companyName,value:form1.companyId}"></cascader-dom>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="reset" class="ivu-btn-reset"  >重置</Button>
                    <Button   class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                </Col>
            </Row>
        </Form>
    
        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" size="small" :loading="buttonLoading"
               highlight-row stripe border :columns="columns3" width="100%" :data="data1">
        </Table>
        <Page :total="pagedata.total"   :fromPage="pagedata.fromPage" :pageSize="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change='sizeChange' show-total show-sizer show-elevator/>

        <Modal title="设备采集项" :transfer=false v-model="collectionItemVisible" :width=800>
            <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label="设备类型名称：" prop="deviceTypeName">
                            <Input type="text" v-model="form1datacopy.deviceTypeName"></Input>
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label="所属公司：" prop="companyId">
                            <cascader-dom class="query-form-el" ref='deviceOrg' @setOrgInfo='setCompanyName' :orgTree="true"
                            :setCurrentName="{label:form1datacopy.companyName,value:form1datacopy.companyId}"></cascader-dom>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <Button style="margin-top:20px" class="ivu-btn-add" icon="md-add" @click="addPlan(form1datacopy.deviceCollectionItemId)">新增
                        </Button>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <Table class="tableClass" border stripe style="margin-top:20px;overflow-y:auto;" size="small"
                                height="400px" :loading="collectionLoading" :columns="collectionItemColumn" :data="collectionItemChildDatas">
                        </Table>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button @click="submitCollectionItems('form1datacopy')" class="ivu-btn-save" :loading="buttonLoading">确定</Button>
                <Button @click="handleCancel" class="ivu-btn-cancel">取消</Button>
            </div>
        </Modal>

        
        <Modal title="设备" :transfer=false v-model="deviceVisible" :width=800>
            <Form label-position="top">
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <Button style="margin-top:20px" class="ivu-btn-add" icon="md-add" @click="addDevice">新增
                        </Button>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <Table class="tableClass" border stripe style="margin-top:20px;overflow-y:auto;" size="small"
                                height="400px" :loading="collectionLoading" :columns="deviceItemColumn" :data="deviceItemDatas">
                        </Table>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button @click="submitDeviceItems()" class="ivu-btn-save" :loading="buttonLoading">确定</Button>
                <Button @click="handleCancel" class="ivu-btn-cancel">取消</Button>
            </div>
        </Modal>

        

        <Modal title="设备采集项" :transfer=false v-model="showCollectionItemVisible" :width=800>
            <Form :model="showdata" :label-width="100">
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label="设备名称：" prop="deviceTypeName">
                           {{showdata.deviceTypeName}}
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label="所属公司：" prop="companyId">
                           {{showdata.companyName}}
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <Table class="tableClass" border stripe style="margin-top:20px;overflow-y:auto;" size="small"
                                height="400px" :loading="collectionLoading" :columns="showCollectionItemColumn" :data="collectionItemChildDatas">
                        </Table>
                    </Col>
                </Row>
            </Form>
             <div slot="footer">
                <Button class='ivu-btn-save' @click="showCollectionItemVisible=false">关闭</Button>
            </div>
        </Modal>

    </Layout>
</template>

<script>
    import cascaderDom from "../../../components/cascader-dom.vue"
    import {sessionStorage} from '../../../common/cacheUtils.js';
    import {
        Api
    } from '../../../api/index.js'
    export default {
        components: {
            cascaderDom
        },
        data() {
            return {
                collectionLoading:false,
                dataInputVisible:false,
                buttonLoading:false,
                switchFlag: false,
                tableHeight: 450,
                add: false,
                currentDeviceCollectionItemId:"",
                form1datacopy:{},
                form1:{
                    companyId:'',
                    companyName:'',
                    deviceTypeName:''
                },
                pagedata: {
                    total: 0, //总条数
                    fromPage: 0, //从n条开始
                    pageSize: 10 //每页多少条
                },
                columns3: [{
                        type: 'index',
                        width: 80,
                        align: 'center'
                    },
                    {
                        title: '设备类型名称',
                        align: 'center',
                        key: 'deviceTypeName'
                    },
                    {
                        title: '二级集团',
                        /*width: 200,*/
                        align: 'center',
                        key: 'twoLevelOrgInfo'
                    },
                    {
                        title: '公司',
                        /*width: 200,*/
                        align: 'center',
                        key: 'orgName'
                    },
                    {
                        title: '操作',
                        fixed: 'right',
                        align: 'center',
                        width:230,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                       click: () => {
                                            this.viewInfo(params.row)
                                        }
                                    }
                                }, '查看'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                       click: () => {
                                            this.currentDeviceCollectionItemId = params.row.deviceCollectionItemId;
                                            this.modifyDevice(params.row)
                                        }
                                    }
                                }, '设备维护'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                       click: () => {
                                            this.modifyInfo(params.row)
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: ( sessionStorage('userId').getObject('userId').loginId != this.Common.admin) && (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)
                                            &&(sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) ? '#d0d0d0' :'red',
                                        pointerEvents: (sessionStorage('userId').getObject('userId').loginId != this.Common.admin) && (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)
                                        &&(essionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined ) ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.removeInfo(params.row.deviceCollectionItemId)
                                        }
                                    }
                                }, '删除')
                        ]);
                        }
                    }
                ],
                data1: [],
                collectionItemVisible:false,
                showCollectionItemVisible:false,
                showdata:{},
                collectionItemChildDatas:[],
                deviceItemDatas:[],
                deviceRealTimeColumn:[],
                deviceVisible:false,
                collectionItemColumn:[
                    {
                        type: 'index',
                        width: 80,
                        align: 'center',
                        title: '序号',
                    },
                    {
                        title: '采集项名称',
                        minWidth: 100,
                        align: 'center',
                        key: 'itemName',
                        render: (h, params) => {
                            return h('Input', {
                                props: {
                                    type: 'text',
                                    value: params.row.itemName
                                },
                                on: {
                                    'on-change': (event) => {
                                        params.row.itemName = event.target.value
                                        this.collectionItemChildDatas[params.index] = params.row;
                                    }
                                }
                            });
                        }
                   },
                   {
                        title: '采集项编码',
                        minWidth: 100,
                        align: 'center',
                        key: 'itemCode',
                        render: (h, params) => {
                            return h('Input', {
                                props: {
                                    type: 'text',
                                    value: params.row.itemCode
                                },
                                on: {
                                    'on-change': (event) => {
                                        params.row.itemCode = event.target.value
                                        this.collectionItemChildDatas[params.index] = params.row;
                                    }
                                }
                            });
                        }
                   },
                   {
                        title: '采集项单位',
                        minWidth: 100,
                        align: 'center',
                        key:'itemUnit',
                        render: (h, params) => {
                            return h('Input', {
                                props: {
                                    type: 'text',
                                    value: params.row.itemUnit
                                },
                                on: {
                                    'on-change': (event) => {
                                        params.row.itemUnit = event.target.value
                                        this.collectionItemChildDatas[params.index] = params.row;
                                    }
                                }
                            });
                        }
                   },
                   {
                        title: '操作',
                        fixed: 'right',
                        align: 'center',
                        width:230,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                       click: () => {
                                            this.deleteItem(params.index)
                                        }
                                    }
                                }, '移除')
                            ])
                        }
                   }
                ],
                deviceItemColumn:[
                    {
                        type: 'index',
                        width: 80,
                        align: 'center',
                        title: '序号',
                    },
                    {
                        title: '设备名称',
                        minWidth: 100,
                        align: 'center',
                        render: (h, params) => {
                            return h('Input', {
                                props: {
                                    type: 'text',
                                    value: params.row.deviceName
                                },
                                on: {
                                    'on-change': (event) => {
                                        params.row.deviceName = event.target.value
                                        this.deviceItemDatas[params.index] = params.row;
                                    }
                                }
                            });
                        }
                   },
                   {
                        title: '设备编码',
                        minWidth: 100,
                        align: 'center',
                        render: (h, params) => {
                            return h('Input', {
                                props: {
                                    type: 'text',
                                    value: params.row.deviceCode
                                },
                                on: {
                                    'on-change': (event) => {
                                        params.row.deviceCode = event.target.value
                                        this.deviceItemDatas[params.index] = params.row;
                                    }
                                }
                            });
                        }
                   },
                   {
                        title: '操作',
                        fixed: 'right',
                        align: 'center',
                        width:230,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                       click: () => {
                                            this.deleteDeviceItem(params.index)
                                        }
                                    }
                                }, '移除')
                            ])
                        }
                   }
                ],
                showCollectionItemColumn:[
                    {
                        type: 'index',
                        width: 80,
                        align: 'center',
                        title: '序号',
                    },
                    {
                        title: '采集项名称',
                        minWidth: 100,
                        align: 'center',
                        key: 'itemName'
                   },
                   {
                        title: '采集项编码',
                        minWidth: 100,
                        align: 'center',
                        key: 'itemCode'
                   },
                   {
                        title: '采集项单位',
                        minWidth: 100,
                        align: 'center',
                        key: 'itemUnit'
                   }
                ]
            }
        },
        mounted: function() {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            //页面加载执行的查询函数,返回的总条数,激活前端分页插件的页码功能.
            this.query();
        },
        methods: {
            switchQuery(flag){
                this.switchFlag = flag;
                if(!this.switchFlag){
                    this.tableHeight = this.tableHeight + 44;
                }else{
                    this.tableHeight = this.tableHeight - 44;
                }
            },
            addInfo(){
                this.form1datacopy = { 
                    deviceCollectionItemId : this.generateUUID(),
                    deviceTypeName: "",
                    orgId: ""
                };
                this.add = true;
                this.collectionItemVisible = true;  
            },
            viewInfo(row){
                this.showdata = row;
                this.showdata.companyId = this.showdata.orgId;
                this.showdata.companyName = this.showdata.orgName;
                this.collectionLoading = true;
                this.$http.get(Api.queryDeviceCollectionItemChildByItemId+"/"+row.deviceCollectionItemId, {}).then(res => {
                    this.collectionItemChildDatas = res.data.data.data;
                    this.collectionLoading = false;
                }).catch(e => {
                    this.collectionLoading = false;
                    this.$Message.error('请求失败');
                })
                this.showCollectionItemVisible = true;
            },
            modifyDevice(row){
                this.collectionLoading = true;
                this.$http.get(Api.queryDeviceByItemId+"/"+row.deviceCollectionItemId, {}).then(res => {
                    this.deviceItemDatas = res.data.data.data;
                    this.collectionLoading = false;
                }).catch(e => {
                    this.collectionLoading = false;
                    this.$Message.error('请求失败');
                })
                this.deviceVisible = true;
            },
            modifyInfo(row){
                this.form1datacopy = row;
                this.form1datacopy.companyId = this.form1datacopy.orgId;
                this.form1datacopy.companyName = this.form1datacopy.orgName;
                setTimeout(()=>{
                    this.$refs.deviceOrg.setCurrentOrg();
                },100)
                this.collectionLoading = true;
                this.$http.get(Api.queryDeviceCollectionItemChildByItemId+"/"+row.deviceCollectionItemId, {}).then(res => {
                    this.collectionItemChildDatas = res.data.data.data;
                   this.collectionLoading = false;
                }).catch(e => {
                    this.$Message.error('请求失败');
                    this.collectionLoading = false;
                })
                 this.collectionItemVisible = true;     
            },
            removeInfo(id){
                this.$http.get(Api.deleteDeviceCollectionItemById+"/"+row.deviceCollectionItemId).then(res => {
                    this.query();
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            sizeChange(size) {
                this.pagedata.pageSize = size
                this.query()
            },
            pageChange(pagenum) {
                this.pagedata.fromPage = pagenum
                this.query()
            },
            query() {
                this.buttonLoading=true
                var companyId = sessionStorage('userId').getObject('userId').companyId;
                if(this.form1.companyId != ''){
                    companyId = this.form1.companyId;
                }
                this.collectionLoading = true;
                this.$http.get(Api.queryDeviceCollectionItemList+"?fromPage="+this.pagedata.fromPage+"&pageSize="+
                this.pagedata.pageSize+"&orgId="+companyId+"&deviceTypeName="+this.form1.deviceTypeName, {}).then(res => {
                    this.pagedata.total = res.data.data.totalSize;
                    this.data1 = res.data.data.data;
                    this.buttonLoading=false;
                    this.collectionLoading = false;
                }).catch(e => {
                    this.collectionLoading = false;
                    this.$Message.error('请求失败');
                })
            },
            submitCollectionItems(name){
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.buttonLoading = true;
                        let userId = sessionStorage('userId').getObject('userId').userId;
                        let orgId = sessionStorage('userId').getObject('userId').companyId;
                        this.form1datacopy.orgId = this.form1datacopy.companyId;
                        if (this.add) {
                            this.form1datacopy.createDate = new Date();
                            this.form1datacopy.createUserId = userId;
                            this.form1datacopy.createOrgId = orgId;
                            this.$http.post(Api.insertDeviceCollectionItem, this.form1datacopy).then((res) => {
                                this.submitCollectionItemChild( this.form1datacopy.deviceCollectionItemId);
                                this.$Message.success("保存成功")
                                this.collectionItemVisible = false;
                                this.query();
                                this.buttonLoading = false;
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.$Message.error("数据获取失败")
                            })
                        } else {
                            this.form1datacopy.updateUserId = userId;
                            this.form1datacopy.updateOrgId = orgId;
                            this.$http.post(Api.updateTopicActivity, this.form1datacopy).then((res) => {
                                this.submitCollectionItemChild(this.form1datacopy.deviceCollectionItemId);
                                this.$Message.success("保存成功")
                                this.collectionItemVisible = false;
                                this.query();
                                this.buttonLoading = false;
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.$Message.error("数据获取失败")
                            })
                        }
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            submitDeviceItems(){
               this.$http.post(Api.insertOrUpdateDeviceByItemId + "/" + this.currentDeviceCollectionItemId, this.deviceItemDatas).then((res) => {
                   this.deviceVisible = false;
                }).catch(e => {
                    this.deviceVisible = false;
                    this.$Message.error('新增失败!');
                })
            },
            async submitCollectionItemChild(id){
                await this.$http.post(Api.insertOrUpdateDeviceCollectionItemChild + "/" + id, this.collectionItemChildDatas).then((res) => {
                }).catch(e => {
                })
            },
            handleCancel(){
                this.deviceVisible = false;
                this.collectionItemVisible = false;
                this.collectionItemChildDatas = [];
            },
            deleteItem(index){
                this.collectionItemChildDatas.splice(index,1);
            },
            deleteDeviceItem(index){
                this.deviceItemDatas.splice(index,1);
            },
            addPlan(deviceCollectionItemId) {
                let item = {
                    deviceCollectionItemId:deviceCollectionItemId,
                    itemName: '',
                    itemCode: '',
                    itemUnit: ''
                }
                this.collectionItemChildDatas.push(item);
            },
            addDevice() {
                this.deviceItemDatas = [];
                let item = {
                    deviceCollectionItemId:this.currentDeviceCollectionItemId,
                    deviceName: '',
                    deviceCode: ''
                }
                this.deviceItemDatas.push(item);
            },
            reset() {
                this.form1.deviceId = '';
                this.form1.companyId = '';
                this.form1.companyName = '';
                this.twoDate = ["",""];
                this.$refs.queryOrgCascader.resetCurrentOrg();
                this.query();
            },
            setQueryCompanyName(data) {
                this.$set(this.form1, 'companyId', data[data.length - 1])
            },
            setCompanyName(data) {
                this.$set(this.form1datacopy, 'companyId', data[data.length - 1])
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                'M+': date.getMonth() + 1,
                'd+': date.getDate(),
                'h+': date.getHours(),
                'm+': date.getMinutes(),
                's+': date.getSeconds()
                };
                for (let k in o) {
                if (new RegExp(`(${k})`).test(fmt)) {
                    let str = o[k] + '';
                    fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                }
                }
                return fmt;
            },
            padLeftZero (str) {
                return ('00' + str).substr(str.length);
            },
            generateUUID() {
                var d = new Date().getTime();
                var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                    var r = (d + Math.random()*16)%16 | 0;
                    d = Math.floor(d/16);
                    return (c=='x' ? r : (r&0x3|0x8)).toString(16);
                });
                return uuid;
            }
        }

    }
</script>

<style scoped lang="css">
    @import '../../../index.css';
</style>
